local skynet = require "skynet"
local filename = "slotmgr.lua"
local filelog = require "filelog"
local queue = require "skynet.queue"
local base = require "base"
local redisdao = require "redisdao"
local tabletool = require "tabletool"
local json = require "cjson"
json.encode_sparse_array(true,1,1)

local SlotTool = require "slottool"

local SERVICE_FEE_RATE = 0.07

local CMD = {}
--
--处理结算结果
--@total_change 总变化值
--@total_water  总流水值
--@total_bet    玩家总下注
--
function CMD.handle_balance_result(gamename, total_change, total_water, total_bet, comment)
    -- filelog.trace("handle_balance_result", gamename, total_change, total_water, total_bet, comment)
    local tax_rate = SlotTool.get_tax_rate_from_redis(gamename)
    local profit_val = math.floor(total_bet * tax_rate * 100) / 100
    local inventory_val = -total_change

    --更新收益值
    local result1 = SlotTool.update_system_profit(gamename, profit_val, comment)
    if result1 then
        inventory_val = inventory_val - profit_val
    end

    --更新库存值，扣除抽水
    -- local service_fee_rate = SlotTool.get_service_fee_rate_from_redis(gamename)
    -- if not service_fee_rate or service_fee_rate <= 0 then
    --     service_fee_rate = 0.06
    -- end
    -- local service_fee_val = math.floor(total_water * service_fee_rate * 100) / 100
    local service_fee_val = math.floor(total_water * SERVICE_FEE_RATE * 100) / 100
    inventory_val = inventory_val - service_fee_val

    return SlotTool.update_system_inventory(gamename, inventory_val, comment)
end

--
--从redis获取系统库存值
--
function CMD.get_inventory_from_redis(gamename)
    return SlotTool.get_static_inventory_from_redis(gamename)
end

--
--获取抽水率
--
function CMD.get_service_fee_rate(gamename)
    return SERVICE_FEE_RATE -- SlotTool.get_service_fee_rate_from_redis(gamename)
end

--
--更新系统收入（机器人，总收入，不是提取）
--
function CMD.update_sys_income(gamename, total_income, comment)
    filelog.trace("update_sys_income", gamename, total_income, comment)
    return SlotTool.update_system_income(gamename, total_income, comment)
end

--
--从redis获取系统收入值（主要是参与游戏的机器人的收入值，总收入，不是提取，可正可负）
--
function CMD.get_service_income(gamename)
    return SlotTool.get_income_from_redis(gamename)
end

-------------------
--
skynet.start(function()
    skynet.dispatch("lua",function(session, source, cmd, ...)
        local f = CMD[cmd]
        if f then
            skynet.retpack(f(...))
        else
            skynet.retpack()
        end
    end)
end)